import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store/index'
Vue.use(VueRouter)
import { Dialog } from 'vant';

// 路由表
const routes = [
  {
    path: '/login',
    name: 'login',
    meta: {
      requiresAuth: false
    },
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/',
    component: () => import('../views/layout/index.vue'),
    children: [
      {
        path: '', // 默认子路由
        name: 'home',
        meta: {
          requiresAuth: false
        },
        component: () => import('../views/home/index.vue')
      },
      {
        path: '/qa',
        name: 'qa',
        meta: {
          requiresAuth: false
        },
        component: () => import('../views/qa/index.vue')
      },
      {
        path: '/video',
        name: 'video',
        meta: {
          requiresAuth: true
        },
        component: () => import('../views/video/index.vue')
      },
      {
        path: '/my',
        name: 'my',
        meta: {
          requiresAuth: false
        },
        component: () => import('../views/my/index.vue')
      }

    ]
  },
  {
    path: '/userChat',
    name: 'userChat',
    meta: {
      requiresAuth: false
    },
    component: () => import('../views/user-chat/index.vue')
  },
  {
    path: '/search',
    name: 'search',
    meta: {
      requiresAuth: false
    },
    component: () => import('@/views/search/index.vue')
  },
  {
    path: '/article/:id',
    name: 'article',
    props: true,
    meta: {
      requiresAuth: false
    },
    component: () => import('@/views/article/index.vue')
  },
  {
    path: '/user',
    name: 'user',
    meta: {
      requiresAuth: false//是否登录后才可以访问
    },
    component: () => import('@/views/user/index.vue')
  }
]

const router = new VueRouter({
  routes
})

// //全局守卫
router.beforeEach((to, from, next) => {

  if (store.state.user) {//已经登录的直接跳出
    return next()
  }

  if (to.meta.requiresAuth) {//登录后才可以访问 
    Dialog.confirm({
      title: '访问提示',
      message: '该功能需要登录才可以访问，是否登录？',
    })
      .then(() => {
        // 确定跳转到登录页
        router.push({
          path: '/login',
          query: {
            redirect: router.currentRoute.fullPath
          }
        })
      })
      .catch(() => {
        // 取消就留在当前页
      })
  } else {//不需要登录的页面直接放行
    next()
  }
})





export default router
